/** http工具类,用于设置请求拦截器和响应拦截器 */
import Request from 'luch-request';
import { assign } from 'lodash-es';
import { Toast } from '@/utils/uniapi/prompt';
import { useUserStore } from '@/store/modules/user';
import { ResultEnum } from '@/enums/httpEnum';
import { router } from '../router';
import config from '../config';
import { checkStatus } from './checkStatus';

const BASE_URL: string = import.meta.env.VITE_API_URL;

// 请求头
const HEADER = {
  'Content-Type': 'application/json;charset=UTF-8;',
  Accept: 'application/json, text/plain, */*',
};

// 放行url
const ANON_URL = [
  config.url.login,
  config.url.captcha,
  config.url.captchaEnabled,
  config.url.tenant,
  config.url.tenantEnabled,
  config.url.secretKey,
];

function createRequest() {
  return new Request({
    // 默认请求地址，可在 .env.** 文件中修改
    baseURL: BASE_URL,
    // 设置超时时间
    timeout: ResultEnum.TIMEOUT as number,
    // 设置请求头
    header: HEADER,
    custom: {
      auth: true,
    },
  });
}

const request = createRequest();

/**
 * 请求拦截器
 */
request.interceptors.request.use(
  (options) => {
    const url = ANON_URL.filter((item: string) => options.url && options.url.indexOf(item) != -1);
    if (options.custom?.auth && url.length == 0) {
      const userStore = useUserStore();
      if (!userStore.isLogin) {
        router.reLaunch(config.route.login);
        return Promise.reject(options);
      }
      options.header = assign(options.header, {
        authorization: userStore.getToken(),
      });
    }
    return options;
  },
  (options) => {
    return Promise.reject(options);
  },
);

/**
 * 响应拦截器
 */
request.interceptors.response.use(
  async (response) => {
    const { data } = response;
    if (data.code === ResultEnum.OVERDUE) {
      Toast(data.message);
      router.reLaunch(config.route.login);
      return Promise.reject(data);
    }
    if (data.code && data.code !== ResultEnum.SUCCESS) {
      checkStatus(data.code, data.message);
      return Promise.reject(data);
    }
    return data;
  },
  (response) => {
    // 请求超时 && 网络错误单独判断
    if (response.errMsg.indexOf('timeout') !== -1) Toast('请求超时！请您稍后重试');
    if (response.errMsg.indexOf('Network Error') !== -1) Toast('网络错误！请您稍后重试');
    return Promise.reject(response);
  },
);

export { request, BASE_URL };
